package com.example.kingdee.kingdeeBridge.kingdeeImpl.impl;

import com.example.kingdee.KingdeeCreate.dto.CreateInDto;
import com.example.kingdee.common.StringUtils;
import com.example.kingdee.common.constant.YiTiConstant;
import com.example.kingdee.exception.ProcedureException;
import com.example.kingdee.kingdeeBridge.common.RequestResult;
import com.example.kingdee.kingdeeBridge.dto.BillWriteInDto;
import com.example.kingdee.kingdeeBridge.entity.SrcBillEntry;
import com.example.kingdee.kingdeeBridge.kingdeeImpl.BillImpl;
import com.example.kingdee.mapper.TBxStMapper;
import com.example.kingdee.sqlTool.SqlTool;
import com.example.kingdee.sqlTool.common.DataObject;
import com.example.kingdee.sqlTool.common.QueryObject;
import com.example.kingdee.sqlTool.sqltoolEnum.FormIdEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.*;

/**
 * 生产领料接口实现类
 */
@Service
public class PickMtlImpl implements BillImpl {

    @Autowired
    private SqlTool sqlTool;

    @Autowired
    private TBxStMapper tBxStMapper;

    @Override
    public Map<String, String> selectTargetBillEntry(String fid) {
        QueryObject inventorySelect = new QueryObject(FormIdEnum.prdPickMtrl);
        ArrayList<String> resultKeyArray = new ArrayList<>();
        inventorySelect.addSelect("FEntity_FEntryID");//明细行id
        resultKeyArray.add("entryId");
        inventorySelect.addSelect("FEntrySrcEnteryId");//原单分录内码
        resultKeyArray.add("srcEntryId");
        inventorySelect.addCondition("fid", fid);
        ArrayList<HashMap<String, Object>> targetEntryInfo = sqlTool.weaveResult(inventorySelect, resultKeyArray);
        //构建收料通知单明细行id和原单行id对应关系
        Map<String, String> keyValue = new HashMap<>();
        for (HashMap<String, Object> sld : targetEntryInfo) {
            keyValue.put(sld.get("srcEntryId").toString(), sld.get("entryId").toString());
        }
        return keyValue;
    }

    @Override
    public RequestResult updateTargetBillEntry(String fid, BillWriteInDto billWriteInDto, Map<String, String> targetInfo) {
        List<SrcBillEntry> srcBillEntryList = billWriteInDto.getSrcBillEntryList();
        //将源单明细按照行id进行分类
        MultiValueMap<String, SrcBillEntry> classFySrcBillEntry = sqlTool.getClassFy(srcBillEntryList);
        //修改收料数量，仓库
        List<Map<String, Object>> detailEntityList = new ArrayList<>();
        for (String srcEntryId : classFySrcBillEntry.keySet()) {
            List<SrcBillEntry> srcBillEntries = classFySrcBillEntry.get(srcEntryId);
            for (int i = 0; i < srcBillEntries.size(); i++) {
                SrcBillEntry srcBillEntry = srcBillEntries.get(i);
                Map<String,Object> detailEntity = new LinkedHashMap<>();
                if (i == 0){
                    //修改下推的行
                    detailEntity.put("FEntryID", targetInfo.get(srcEntryId));//行id 必填
                }else {
                    //查询用料清单原单信息
                    Map<String, Object> srcPoorInfo = tBxStMapper.getSrcPpBomInfo(srcEntryId);

                    //构建基础信息
                    detailEntity.put("FEntryID", 0);//行id 必填
//                    detailEntity.put("FSrcEntryId", srcEntryId);//源单分录内码 必填
                    HashMap<String, Object> ownerId = new HashMap<>();
                    ownerId.put("fnumber", srcPoorInfo.get("itemOwner"));
                    HashMap<String, Object> stockUnitId = new HashMap<>();
                    stockUnitId.put("fnumber", srcPoorInfo.get("unitNumber"));
                    HashMap<String, Object> materialId = new HashMap<>();
                    materialId.put("fnumber", srcPoorInfo.get("itemNumber"));
                    HashMap<String, Object> moMaterialId = new HashMap<>();
                    moMaterialId.put("fnumber", srcPoorInfo.get("moItemNumber"));
                    HashMap<String, Object> deptNumber = new HashMap<>();
                    deptNumber.put("fnumber", srcPoorInfo.get("deptNumber"));
                    detailEntity.put("FMaterialId", materialId);//物料id 必填
                    detailEntity.put("FUnitID", stockUnitId);//单位 必填
                    detailEntity.put("FStockUnitId", stockUnitId);//库存单位 必填
                    detailEntity.put("FBaseUnitId", stockUnitId);//基本单位 必填
                    detailEntity.put("FMoBillNo", srcPoorInfo.get("moBillNo"));//生产订单编号 必填
                    detailEntity.put("FPPBomBillNo", srcPoorInfo.get("srcBillNo"));//用料清单编号 必填
                    detailEntity.put("FPPBomEntryId", Integer.parseInt(srcEntryId));//用料清单分录id 必填
                    detailEntity.put("FEntrySrcEnteryId", Integer.parseInt(srcEntryId));//源单分录内码 必填
                    detailEntity.put("FMoEntryId", srcPoorInfo.get("moEntryId"));//生产订单分录内码 必填
                    detailEntity.put("FParentMaterialId", moMaterialId);//生产订单物料id 必填
                    detailEntity.put("FOwnerId", ownerId);//货主 必填
                    detailEntity.put("FParentOwnerId", ownerId);//产品货主 必填
                    detailEntity.put("FSrcBillNo", srcPoorInfo.get("srcBillNo"));//源单编号 必填
                    detailEntity.put("FEntrySrcEntrySeq", srcPoorInfo.get("moSeq"));//源单行号 必填
                    detailEntity.put("FEntryWorkShopId", deptNumber);//车间 必填
                    detailEntity.put("FSrcBillType", "PRD_PPBOM");//原单类型 必填


                    //构建原单关联关系
                    List<Map<String, Object>> detailLinkList = new ArrayList<>();
                    HashMap<String, Object> detailLink = new HashMap<>();
                    detailLink.put("FEntity_Link_FFlowId", "");//业务流程图
                    detailLink.put("FEntity_Link_FFlowLineId", "");//推进路线
                    detailLink.put("FEntity_Link_FRuleId", YiTiConstant.PRD_PICK_MTRL);//转换规则
                    detailLink.put("FEntity_Link_FSTableId", srcPoorInfo.get("srcId"));//源单表内码
                    detailLink.put("FEntity_Link_FSTableName", "T_PRD_PPBOMENTRY");//源单表
                    detailLink.put("FEntity_Link_FSBillId", srcPoorInfo.get("srcId"));//源单内码
                    detailLink.put("FEntity_Link_FSId", Integer.parseInt(srcEntryId));//源单分录内码
                    detailLinkList.add(detailLink);
                    detailEntity.put("FEntity_Link", detailLinkList);//源单关联关系 必填
                }
                //辅助属性
                Map<String,Object> auxPropId = new LinkedHashMap<>();
                Map<String,Object> level = new LinkedHashMap<>();
                level.put("fnumber", srcBillEntry.getReserved3());//等级
                Map<String,Object> ply = new LinkedHashMap<>();
                ply.put("fnumber", srcBillEntry.getReserved4());//厚度
                auxPropId.put("FAUXPROPID__FF100001", level);
                auxPropId.put("FAUXPROPID__FF100002", ply);
                //实发数量
                detailEntity.put("FActualQty", srcBillEntry.getQty());
                //申请数量
                detailEntity.put("FAppQty", srcBillEntry.getQty());
                //基本数量
                detailEntity.put("FBaseActualQty", srcBillEntry.getQty());
                //基本数量
                detailEntity.put("FBaseStockActualQty", srcBillEntry.getQty());
                //辅助属性
                detailEntity.put("FAuxPropId", auxPropId);
                if(!StringUtils.isEmpty(srcBillEntry.getStockNumber())){
                    HashMap<String, Object> stockId = new HashMap<>();
                    stockId.put("fnumber", srcBillEntry.getStockNumber());
                    detailEntity.put("FStockId", stockId);//仓库 必填
                }
                if (!StringUtils.isEmpty(srcBillEntry.getStockLocNumber())){
                    String stockLocFlexNumber = sqlTool.getStockLocFlexNumber(srcBillEntry.getStockLocNumber(), srcBillEntry.getStockNumber());
                    //仓位
                    Map<String, Object> shippingSpaceNumber = new HashMap<>(); //位置仓位值编码 必填
                    shippingSpaceNumber.put("FNumber", srcBillEntry.getStockLocNumber());
                    Map<String, Object> stockLocId = new HashMap<>();
                    stockLocId.put("FSTOCKLOCID__" + stockLocFlexNumber, shippingSpaceNumber);
                    detailEntity.put("FStockLocId", stockLocId);
                }
                detailEntityList.add(detailEntity);
            }
        }
        //修改
        DataObject order = new DataObject(FormIdEnum.prdPickMtrl);
        order.setAttribute("FID", fid);
        order.setAttribute("FEntity", detailEntityList);//订单明细
        try {
            Map<String, Object> result = sqlTool.editForDataObject(order);
            if (result.get("code").toString().equals("200")){
                return RequestResult.ofSuccess(result);
            }else {
                return RequestResult.ofError(result.get("msg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ProcedureException("无法调用云星空接口");
        }
    }

    /**
     *
     * @param fid 表id
     * @param targetInfo 目标单据行id和源单行id对应关系
     * @return
     */
    public RequestResult updateTargetBillEntry(String fid, Map<String, String> targetInfo, CreateInDto createInDto) {
        String stockNumber = createInDto.getReserved1() == null ? "" : String.valueOf(createInDto.getReserved1());
        String stockLocNumber = createInDto.getReserved2() == null ? "" : String.valueOf(createInDto.getReserved2());
        //修改收料数量，仓库
        List<Map<String, Object>> detailEntityList = new ArrayList<>();
        for (String entryId : targetInfo.keySet()) {
            //查询物料等级以及厚度
            Integer itemId = tBxStMapper.getPickItemId(entryId);
            List<Map<String, Object>> itemLevelAanPlyList = tBxStMapper.getItemLevelAanPlyList(itemId, createInDto.getReserved5());
            if (itemLevelAanPlyList != null && itemLevelAanPlyList.size() != 0){
                //拆分行逻辑
                editListInfo(entryId, targetInfo.get(entryId), stockNumber, stockLocNumber, detailEntityList, itemLevelAanPlyList);
            }else {
                //不拆分行
                editOneInfo(entryId, stockNumber, stockLocNumber, detailEntityList);
            }

        }
        //修改单据
        DataObject order = new DataObject(FormIdEnum.prdPickMtrl);
        order.setAttribute("FID", fid);
        order.setAttribute("FEntity", detailEntityList);//订单明细
        try {
            Map<String, Object> result = sqlTool.editForDataObject(order);
            if (result.get("code").toString().equals("200")){
                return RequestResult.ofSuccess(result);
            }else {
                return RequestResult.ofError(result.get("msg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ProcedureException("无法调用云星空接口");
        }
    }

    //构建领料单多行
    public void editListInfo(String entryId, String srcEntryId, String stockNumber, String stockLocNumber, List<Map<String, Object>> detailEntityList, List<Map<String, Object>> itemLevelAanPlyList){
        for (int i = 0; i < itemLevelAanPlyList.size(); i++) {
            Map<String, Object> itemLevelAanPly = itemLevelAanPlyList.get(i);
            Map<String,Object> detailEntity = new LinkedHashMap<>();
            if (i == 0){
                //修改下推的行
                detailEntity.put("FEntryID", entryId);//行id 必填
            }else {
                //查询用料清单原单信息
                Map<String, Object> srcPoorInfo = tBxStMapper.getSrcPpBomInfo(srcEntryId);
                //构建基础信息
                detailEntity.put("FEntryID", 0);//行id 必填
                HashMap<String, Object> ownerId = new HashMap<>();
                ownerId.put("fnumber", srcPoorInfo.get("itemOwner"));
                HashMap<String, Object> stockUnitId = new HashMap<>();
                stockUnitId.put("fnumber", srcPoorInfo.get("unitNumber"));
                HashMap<String, Object> materialId = new HashMap<>();
                materialId.put("fnumber", srcPoorInfo.get("itemNumber"));
                HashMap<String, Object> moMaterialId = new HashMap<>();
                moMaterialId.put("fnumber", srcPoorInfo.get("moItemNumber"));
                HashMap<String, Object> deptNumber = new HashMap<>();
                deptNumber.put("fnumber", srcPoorInfo.get("deptNumber"));
                detailEntity.put("FMaterialId", materialId);//物料id 必填
                detailEntity.put("FUnitID", stockUnitId);//单位 必填
                detailEntity.put("FStockUnitId", stockUnitId);//库存单位 必填
                detailEntity.put("FBaseUnitId", stockUnitId);//基本单位 必填
                detailEntity.put("FMoBillNo", srcPoorInfo.get("moBillNo"));//生产订单编号 必填
                detailEntity.put("FPPBomBillNo", srcPoorInfo.get("srcBillNo"));//用料清单编号 必填
                detailEntity.put("FPPBomEntryId", Integer.parseInt(srcEntryId));//用料清单分录id 必填
                detailEntity.put("FEntrySrcEnteryId", Integer.parseInt(srcEntryId));//源单分录内码 必填
                detailEntity.put("FMoEntryId", srcPoorInfo.get("moEntryId"));//生产订单分录内码 必填
                detailEntity.put("FParentMaterialId", moMaterialId);//生产订单物料id 必填
                detailEntity.put("FOwnerId", ownerId);//货主 必填
                detailEntity.put("FParentOwnerId", ownerId);//产品货主 必填
                detailEntity.put("FSrcBillNo", srcPoorInfo.get("srcBillNo"));//源单编号 必填
                detailEntity.put("FEntrySrcEntrySeq", srcPoorInfo.get("moSeq"));//源单行号 必填
                detailEntity.put("FEntryWorkShopId", deptNumber);//车间 必填
                detailEntity.put("FSrcBillType", "PRD_PPBOM");//原单类型 必填


                //构建原单关联关系
                List<Map<String, Object>> detailLinkList = new ArrayList<>();
                HashMap<String, Object> detailLink = new HashMap<>();
                detailLink.put("FEntity_Link_FFlowId", "");//业务流程图
                detailLink.put("FEntity_Link_FFlowLineId", "");//推进路线
                detailLink.put("FEntity_Link_FRuleId", YiTiConstant.PRD_PICK_MTRL);//转换规则
                detailLink.put("FEntity_Link_FSTableId", srcPoorInfo.get("srcId"));//源单表内码
                detailLink.put("FEntity_Link_FSTableName", "T_PRD_PPBOMENTRY");//源单表
                detailLink.put("FEntity_Link_FSBillId", srcPoorInfo.get("srcId"));//源单内码
                detailLink.put("FEntity_Link_FSId", Integer.parseInt(srcEntryId));//源单分录内码
                detailLinkList.add(detailLink);
                detailEntity.put("FEntity_Link", detailLinkList);//源单关联关系 必填
            }
            //辅助属性
            Map<String,Object> auxPropId = new LinkedHashMap<>();
            Map<String,Object> level = new LinkedHashMap<>();
            level.put("fnumber", itemLevelAanPly.get("itemlevel"));//等级
            Map<String,Object> ply = new LinkedHashMap<>();
            ply.put("fnumber", itemLevelAanPly.get("ply"));//厚度
            auxPropId.put("FAUXPROPID__FF100001", level);
            auxPropId.put("FAUXPROPID__FF100002", ply);
            //实发数量
            detailEntity.put("FActualQty", itemLevelAanPly.get("realQty"));
            //申请数量
            detailEntity.put("FAppQty", itemLevelAanPly.get("realQty"));
            //基本数量
            detailEntity.put("FBaseActualQty", itemLevelAanPly.get("realQty"));
            //基本数量
            detailEntity.put("FBaseStockActualQty", itemLevelAanPly.get("realQty"));
            //辅助属性
            detailEntity.put("FAuxPropId", auxPropId);
            if(!StringUtils.isEmpty(stockNumber)){
                HashMap<String, Object> stockId = new HashMap<>();
                stockId.put("fnumber", stockNumber);
                detailEntity.put("FStockId", stockId);//仓库 必填
            }
            if (!StringUtils.isEmpty(stockLocNumber)){
                String stockLocFlexNumber = sqlTool.getStockLocFlexNumber(stockLocNumber, stockNumber);
                //仓位
                Map<String, Object> shippingSpaceNumber = new HashMap<>(); //位置仓位值编码 必填
                shippingSpaceNumber.put("FNumber", stockLocNumber);
                Map<String, Object> stockLocId = new HashMap<>();
                stockLocId.put("FSTOCKLOCID__" + stockLocFlexNumber, shippingSpaceNumber);
                detailEntity.put("FStockLocId", stockLocId);
            }
            detailEntityList.add(detailEntity);
        }
    }

    //构建领料单单行
    public void editOneInfo(String entryId, String stockNumber, String stockLocNumber, List<Map<String, Object>> detailEntityList){
        Map<String,Object> detailEntity = new LinkedHashMap<>();
        detailEntity.put("FEntryId", entryId);//行id 必填
        if(!StringUtils.isEmpty(stockNumber)){
            HashMap<String, Object> stockId = new HashMap<>();
            stockId.put("fnumber", stockNumber);
            detailEntity.put("FStockId", stockId);//仓库 必填
        }
        if (!StringUtils.isEmpty(stockLocNumber)){
            String stockLocFlexNumber = sqlTool.getStockLocFlexNumber(stockLocNumber, stockNumber);
            //仓位
            Map<String, Object> shippingSpaceNumber = new HashMap<>(); //位置仓位值编码 必填
            shippingSpaceNumber.put("FNumber", stockLocNumber);
            Map<String, Object> stockLocId = new HashMap<>();
            stockLocId.put("FSTOCKLOCID__" + stockLocFlexNumber, shippingSpaceNumber);
            detailEntity.put("FStockLocId", stockLocId);
        }
        detailEntityList.add(detailEntity);
    }

//    /**
//     *
//     * @param fid 表id
//     * @param targetInfo 目标单据行id和源单行id对应关系
//     * @return
//     */
//    public RequestResult updateTargetBillEntry(String fid, Map<String, String> targetInfo, CreateInDto createInDto) {
//        String stockNumber = createInDto.getReserved1() == null ? "" : String.valueOf(createInDto.getReserved1());
//        String stockLocNumber = createInDto.getReserved2() == null ? "" : String.valueOf(createInDto.getReserved2());
//        //修改收料数量，仓库
//        List<Map<String, Object>> detailEntityList = new ArrayList<>();
//        for (String entryId : targetInfo.keySet()) {
//            //查询物料等级以及厚度
//            Integer itemId = tBxStMapper.getPickItemId(entryId);
//            Map<String, Object> levelAndOly = tBxStMapper.getItemLevelAanPly(itemId, createInDto.getReserved5());
//            Map<String,Object> detailEntity = new LinkedHashMap<>();
//            detailEntity.put("FEntryId", entryId);//行id 必填
//            if (levelAndOly != null){
//                //辅助属性
//                Map<String,Object> auxPropId = new LinkedHashMap<>();
//                Map<String,Object> level = new LinkedHashMap<>();
//                level.put("fnumber", levelAndOly.get("itemlevel"));//等级
//                Map<String,Object> ply = new LinkedHashMap<>();
//                ply.put("fnumber", levelAndOly.get("ply"));//厚度
//                auxPropId.put("FAUXPROPID__FF100001", level);
//                auxPropId.put("FAUXPROPID__FF100002", ply);
//                //辅助属性
//                detailEntity.put("FAuxPropId", auxPropId);
//                //实发数量
//                if (levelAndOly.get("realQty") != null){
//                    detailEntity.put("FActualQty", levelAndOly.get("realQty"));
//                }
//            }
//            if(!StringUtils.isEmpty(stockNumber)){
//                HashMap<String, Object> stockId = new HashMap<>();
//                stockId.put("fnumber", stockNumber);
//                detailEntity.put("FStockId", stockId);//仓库 必填
//            }
//            if (!StringUtils.isEmpty(stockLocNumber)){
//                String stockLocFlexNumber = sqlTool.getStockLocFlexNumber(stockLocNumber, stockNumber);
//                //仓位
//                Map<String, Object> shippingSpaceNumber = new HashMap<>(); //位置仓位值编码 必填
//                shippingSpaceNumber.put("FNumber", stockLocNumber);
//                Map<String, Object> stockLocId = new HashMap<>();
//                stockLocId.put("FSTOCKLOCID__" + stockLocFlexNumber, shippingSpaceNumber);
//                detailEntity.put("FStockLocId", stockLocId);
//            }
//            detailEntityList.add(detailEntity);
//        }
//        //修改单据
//        DataObject order = new DataObject(FormIdEnum.prdPickMtrl);
//        order.setAttribute("FID", fid);
//        order.setAttribute("FEntity", detailEntityList);//订单明细
//        try {
//            Map<String, Object> result = sqlTool.editForDataObject(order);
//            if (result.get("code").toString().equals("200")){
//                return RequestResult.ofSuccess(result);
//            }else {
//                return RequestResult.ofError(result.get("msg").toString());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new ProcedureException("无法调用云星空接口");
//        }
//    }

    @Override
    public void postPosition(String billNo) {

    }

    @Override
    public void auditTargetBill(String billNo) {
        //提交审核
        sqlTool.auditBill(billNo, FormIdEnum.prdPickMtrl);
    }

    @Override
    public void deleteTargetBill(String fid) {
        sqlTool.deleteBill(fid, FormIdEnum.prdPickMtrl);
    }

    public void unAuditDataObject(String fid) {
        DataObject unAuditDataObject = new DataObject(FormIdEnum.prdPickMtrl);
        unAuditDataObject.addIds(fid);
        sqlTool.unAuditBatchData(unAuditDataObject);
    }
}
